package v5

import (
	"fmt"
	"log"
	v4 "mindonmap/api/v4"
	"mindonmap/models"
	"mindonmap/pkgs/e"
	"mindonmap/validation"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

type Template struct {
	ID           int    `json:"id"`
	MdId         int    `json:"md_id"`
	Title        string `json:"title"`
	Description  string `json:"description"`
	Keywords     string `json:"keywords"`
	CategoriesID int    `json:"categories_id"`
	SceneId      int    `json:"scene_id"`
	PayType      int    `json:"pay_type"`
	Price        string `json:"price"`
}

type TemplateOperate struct {
	TemplateId int `json:"template_id"`
	Action     int `json:"action"`
}

func AddTemplate(c *gin.Context) {
	var json Template
	if err := c.ShouldBindJSON(&json); err != nil { // 推荐使用ShouldBindJSON
		c.JSON(http.StatusOK, gin.H{
			"code": e.INVALID_PARAMS,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": nil,
		})
		return
	}
	// timeint := int32(time.Now().Unix())
	// fmt.Printf("时间戳:%+v", timeint)

	fmt.Printf("绑定后的 Template 结构体: %+v\n", json)

	// Userid := 218
	Userid, err := v4.GetUserID(c)
	fmt.Printf("绑定后的 userid: %+v\n", Userid)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT,
			"msg":  e.GetMsg(e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT),
			"data": make(map[string]interface{}),
		})
		return
	}

	// var total = v4.MindMapTotal(Userid)
	// pc := v4.NewPrivilegeController()
	// var isvip = v4.IsVip(c)
	// var CheckPriv bool
	// if isvip {
	// 	CheckPriv = pc.CheckPrivilege("vip", "cloud_storage_limit", total)
	// } else {
	// 	CheckPriv = pc.CheckPrivilege("free", "cloud_storage_limit", total)
	// }
	// if !CheckPriv {
	// 	c.JSON(http.StatusOK, gin.H{
	// 		"code": e.ERROR_AUTH_PERMISSION,
	// 		"msg":  e.GetMsg(e.ERROR_AUTH_PERMISSION),
	// 		"data": make(map[string]interface{}),
	// 	})
	// 	return
	// }
	code := e.INVALID_PARAMS
	data := make(map[string]interface{})
	MdContent, err := models.GetMindMapDetail(json.MdId)
	fmt.Printf("mind详情: %+v\n", MdContent)
	if err != nil || len(MdContent) == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": e.ERROR_NOT_EXIST_ARTICLE,
			"msg":  e.GetMsg(e.ERROR_NOT_EXIST_ARTICLE),
			"data": make(map[string]interface{}),
		})
		return
	}
	data["uid"] = Userid
	data["md_id"] = json.MdId
	data["title"] = json.Title
	data["description"] = json.Description
	data["keywords"] = json.Keywords
	data["categories_id"] = json.CategoriesID
	data["pay_type"] = json.PayType
	data["scene_id"] = json.SceneId
	data["price"] = json.Price
	for _, mind := range MdContent {
		data["mind_id"] = mind.Mindid
		data["image_url"] = mind.Image
		fmt.Printf("ID: %d\n", mind.ID)
	}
	msg := 0

	success, err := models.AddTemplate(data)
	if err != nil {
		// 处理错误
		println("插入模板失败:", err.Error())
	} else if success {
		println("插入模板成功")
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  msg,
		"data": data,
	})

}

// 模板列表
func TemplateList(c *gin.Context) {
	data := make(map[string]interface{})
	pageStr := c.DefaultQuery("page", "1")
	limitStr := c.DefaultQuery("limit", "10")
	title := c.Query("title")
	categoryIDStr := c.Query("category_id")
	sceneIdStr := c.Query("scene_id")
	payTypeStr := c.Query("pay_type")
	orderstr := c.Query("order")

	order, _ := strconv.Atoi(orderstr)
	page, _ := strconv.Atoi(pageStr)
	limit, _ := strconv.Atoi(limitStr)
	offset := (page - 1) * limit

	var categoryID int
	if categoryIDStr != "" {
		categoryID, _ = strconv.Atoi(categoryIDStr)
	}
	var sceneId int
	if sceneIdStr != "" {
		sceneId, _ = strconv.Atoi(sceneIdStr)
	}
	var payType int
	if payTypeStr != "" {
		payType, _ = strconv.Atoi(payTypeStr)
	}

	code := e.INVALID_PARAMS
	valid := validation.Validation{}
	if !valid.HasErrors() {
		code = e.SUCCESS
		data["list"] = models.GetTemplateList(limit, offset, title, categoryID, sceneId, payType, order)
		data["total"] = models.GetTemplateTotal(title, categoryID, sceneId, payType)
	} else {
		for _, err := range valid.Errors {
			log.Printf("err.key: %s, err.message: %s", err.Key, err.Message)
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": data,
	})

}

// 添加模板操作
func AddTemplateOperate(c *gin.Context) {
	var json TemplateOperate
	if err := c.ShouldBindJSON(&json); err != nil { // 推荐使用ShouldBindJSON
		c.JSON(http.StatusOK, gin.H{
			"code": e.INVALID_PARAMS,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": nil,
		})
		return
	}

	// Userid := 218
	Userid, err := v4.GetUserID(c)
	fmt.Printf("绑定后的 userid: %+v\n", Userid)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT,
			"msg":  e.GetMsg(e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT),
			"data": make(map[string]interface{}),
		})
		return
	}
	code := e.INVALID_PARAMS
	operate_uid := models.GetTemplateUid(json.TemplateId)
	result, err := models.AddTemplateCollect(Userid, operate_uid, json.TemplateId, json.Action)
	var count = 0
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": code,
			"msg":  err,
			"data": count,
		})
	} else {
		code = e.SUCCESS
		fmt.Println("result: ", result)
		if result == 1 {
			count = models.TemplateIncremental(json.Action, json.TemplateId)
		} else if result == 2 {
			count = models.TemplateDecremental(json.Action, json.TemplateId)
		}
		c.JSON(http.StatusOK, gin.H{
			"code": code,
			"msg":  e.GetMsg(code),
			"data": count,
		})
	}

}

// 模板列表
func MyCollertTemplateList(c *gin.Context) {

	data := make(map[string]interface{})
	pageStr := c.DefaultQuery("page", "1")
	limitStr := c.DefaultQuery("limit", "10")
	title := c.Query("title")
	categoryIDStr := c.Query("category_id")
	sceneIdStr := c.Query("scene_id")
	payTypeStr := c.Query("pay_type")

	page, _ := strconv.Atoi(pageStr)
	limit, _ := strconv.Atoi(limitStr)
	offset := (page - 1) * limit

	var categoryID int
	if categoryIDStr != "" {
		categoryID, _ = strconv.Atoi(categoryIDStr)
	}
	var sceneId int
	if sceneIdStr != "" {
		sceneId, _ = strconv.Atoi(sceneIdStr)
	}
	var payType int
	if payTypeStr != "" {
		payType, _ = strconv.Atoi(payTypeStr)
	}

	user_id, err := v4.GetUserID(c)
	fmt.Printf("绑定后的 userid: %+v\n", user_id)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT,
			"msg":  e.GetMsg(e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT),
			"data": make(map[string]interface{}),
		})
		return
	}

	code := e.INVALID_PARAMS
	valid := validation.Validation{}
	if !valid.HasErrors() {
		code = e.SUCCESS
		templates, err := models.GetMyCollectedTemplates(user_id, title, page, offset)
		if err != nil {
			fmt.Print(err)
		}
		data["list"] = templates
		data["total"] = models.GetTemplateTotal(title, categoryID, sceneId, payType)
	} else {
		for _, err := range valid.Errors {
			log.Printf("err.key: %s, err.message: %s", err.Key, err.Message)
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": data,
	})

}
